using System;
using System.Web;
using System.Web.Caching;

namespace Shinkansen.Model
{
    public class CachedStaticResource : IStaticResource
    {
        private readonly IStaticResource _resource;
        private readonly ResourceInformation _ri;
        private static readonly object _sycnRoot = new object ();


        /// <summary>
        /// Initializes a new instance of the <see cref="CachedStaticResource"/> class.
        /// </summary>
        /// <param name="resource">The resource.</param>
        /// <param name="ri">The ri.</param>
        public CachedStaticResource (IStaticResource resource, ResourceInformation ri)
        {
            _resource = resource;
            _ri = ri;
        }

        /// <summary>
        /// Gets the content.
        /// </summary>
        /// <returns></returns>
        public byte[] GetContent ()
        {
            string  originalToken = _ri.OriginalToken;
            Cache   cache = HttpRuntime.Cache;

            byte[] content = (byte[]) cache [originalToken];

            if (content == null)
            {
                lock (_sycnRoot)
                {
                    content = (byte[]) cache [originalToken];

                    if (content == null)
                    {
                        content = _resource.GetContent ();
                        cache.Insert (originalToken, content, null, Cache.NoAbsoluteExpiration, TimeSpan.FromHours (1));
                    }
                }
            }

            return content;
        }
    }
}